<template>
  <div class="mainContent">
    <div class="header">
      <span class="headerLeft">商品清单</span>
      <span class="headerRight">
        <span @click="clickAllPickUp"><svg-icon class="transform" icon-class="upList" />&nbsp;全部收起</span>
        <span @click="clickToEdit"><svg-icon icon-class="edit" />&nbsp;{{ isEdit?'完成':'编辑' }}</span>
      </span>
    </div>
    <div class="contentList">
      <van-list
        v-model="loading"
        :finished="finished"
        :offset="80"
        @load="loadMore">
        <div v-for="(goodsItem,goodsIndex) in dataList" :key="goodsIndex" class="item">
          <div slot="title" class="title">
            <van-checkbox v-model="goodsItem.goods_isChecked" class="titleLeft" @change="handleChangeGoodsChecked(goodsItem)"/>
            <div class="titleRight" @click="clickToGoodsDetail(goodsItem.item_id)">
              <img v-if="goodsItem.image_url" :src="goodsItem.image_url" class="leftImg" alt="">
              <img v-else src="../../assets/images/loadingError.png" class="leftImg" alt="">
              <span class="titleWord">{{ goodsItem.title }}</span>
            </div>
            <span class="iconBox" @click="toggleActive(goodsItem,goodsIndex)">{{ goodsItem.active?'收起':'展开' }} <svg-icon :class="goodsItem.active?'transform':'icon'" icon-class="icon_right" /></span>
          </div>
          <div v-show="goodsItem.active" class="item-content">
            <div class="content-list">
              <div v-for="(sku,skuIndex) in goodsItem.sku_lists" :key="skuIndex" class="list-item">
                <van-checkbox v-model="sku.sku_isChecked" class="titleLeft" @change="handleChangeSkuChecked(goodsItem,sku)" />
                <span class="checkBox-content">
                  <span class="left-item">
                    <span style="overflow-x: hidden;word-break: break-all;text-overflow: ellipsis">{{ sku.sku_name }}</span>
                    <span><i class="font-colorRed">¥{{ Number(sku.price).toFixed(getitem.item_price_p) }}</i> / {{ goodsItem.unit_name }}</span>
                  </span>
                  <span class="right-item"><van-stepper v-model="sku.sku_num" integer @change="handleChangeSkuNum(sku)" /></span>
                </span>
              </div>
            </div>
          </div>
          <div class="total-item">
            <span class="total-itemNum">共{{ getGoodsItemNumAndPrice(goodsIndex).totalNum }}件商品</span>
            <span class="total-itemPrice">¥{{ getGoodsItemNumAndPrice(goodsIndex).totalPrice.toFixed(getitem.item_price_p) }}</span>
          </div>
        </div>
      </van-list>
    </div>
    <div v-if="dataList.length !== 0" class="footerBtn">
      <span><van-checkbox v-model="allChecked" class="footerItem" @change="setAllChoose"/></span>
      <div class="footerContent">
        <span class="all">全选</span>
        <span v-if="!isEdit" class="totalContent1">
          <span class="content">
            <span>合计:
              <span class="font-colorRed price">¥ <span class="int">{{ getTotalNumAndPrice().totalPrice.toFixed(getitem.item_price_p).split('.')[0] }}</span><span class="floor">.{{ getTotalNumAndPrice().totalPrice.toFixed(getitem.item_price_p).split('.')[1] }}</span></span>
              <br>
              <span class="tip">共{{ getTotalNumAndPrice().kindNum }}种, 总数 {{ getTotalNumAndPrice().totalNum }}</span>
            </span>
          </span>
          <span class="footerBtnItem" @click="clickToOrder">立即结算</span>
        </span>
        <span v-if="isEdit" class="totalContent2">
          <van-button class="btn btn-orange" size="small" type="default" @click="isEdit=!isEdit">取 消</van-button>
          &nbsp;&nbsp;
          <van-button class="btn btn-orange" size="small" type="default" @click="deleteGoods">删 除</van-button>
        </span>
      </div>
    </div>
    <div v-if="dataList.length === 0&&!loading" class="noData small">
      <div class="content">
        <img src="../../assets/images/noData/noDataGoods.png" alt="">
        <div class="text">暂无商品
          <span class="font-colorOrange" @click="$router.push({name:'goods-index'})">点击添加商品</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { GetCartItem, PutBatchDelCartItem, PutClearCart, setCartItemNum } from '@/api/cart'
export default {
  name: 'Index',
  data() {
    return {
      allActive: false,
      loading: false,
      finished: false,
      activeNames: ['1'],
      dataList: [],
      isEdit: false,
      allChecked: false,
      showIndex: undefined,
      searchData: {
        p: 1,
        pernum: 10
      }
    }
  },
  computed: {
    ...mapGetters([
      'getitem'
    ])
  },
  methods: {
    // 分步加载
    loadMore() {
      this.loading = true
      this.getGoodsItemsList()
    },
    // 获取购物车中的商品
    getGoodsItemsList() {
      GetCartItem(this.searchData).then(res => {
        const data = res.data
        if (data.status_code === 200) {
          this.searchData.p++
          data.data.list.forEach(item => {
            this.$set(item, 'goods_isChecked', false)
          })
          this.dataList = [...this.dataList, ...data.data.list] // 数组拼接
          if (this.dataList.length >= data.data.count) {
            this.finished = true
            this.loading = false
          }
          this.setDataFormatting(this.dataList)
        } else {
          this.dataList = []
        }
      })
    },
    // 修改数据的格式
    setDataFormatting(data) {
      const completeData = []
      data.forEach((item) => {
        this.$set(item, 'active', true)
        if (completeData[item.item_id] === undefined) {
          completeData[item.item_id] = item
          this.$set(completeData[item.item_id], 'sku_lists', [])
          completeData[item.item_id].num = item.num
          completeData[item.item_id].price = parseFloat(item.price)
          completeData[item.item_id].sku_lists.push({
            cart_id: item.cart_id,
            item_id: item.item_id,
            sku_id: item.sku_id,
            sku_name: item.sku_name,
            price: item.price,
            sku_num: item.num,
            maxnum: item.maxnum,
            mininum: item.mininum,
            sku_isChecked: false
          })
        } else {
          completeData[item.item_id].num += item.num
          completeData[item.item_id].price += parseFloat(item.price)
          completeData[item.item_id].sku_lists.push({
            cart_id: item.cart_id,
            item_id: item.item_id,
            sku_id: item.sku_id,
            sku_name: item.sku_name,
            price: item.price,
            sku_num: item.num,
            maxnum: item.maxnum,
            mininum: item.mininum,
            sku_isChecked: false
          })
        }
      })
      const NewArr = []
      for (const key in completeData) {
        NewArr.push(completeData[key])
      }
      this.dataList = NewArr
    },
    // 切换单条的展开收起
    toggleActive(item, index) {
      this.$set(this.dataList[index], 'active', !this.dataList[index].active)
    },
    // 顶部编辑按钮
    clickToEdit() {
      this.isEdit = !this.isEdit
    },
    // 全部收起
    clickAllPickUp() {
      this.dataList.forEach(item => {
        item.active = false
      })
    },
    // 删除购物车商品
    deleteGoods() {
      this.$toast.loading({
        duration: 1500,
        message: '请稍后...'
      })
      if (this.allChecked) { // 清空购物车
        PutClearCart().then(res => {
          const data = res.data
          if (data.status_code === 200) {
            this.$toast.success({
              duration: 1500,
              message: '清空购物车'
            })
            this.isEdit = false
            this.dataList = []
            this.searchData.p = 1
            this.getGoodsItemsList()
            this.$store.dispatch('setCartItemNumFn')
          } else {
            this.$toast.fail({
              duration: 1500,
              message: data.message
            })
          }
        })
      } else { // 批量删除商品
        const data = {
          cart_ids: []
        }
        this.dataList.forEach(goodsItem => {
          goodsItem.sku_lists.forEach(sku => {
            if (sku.sku_isChecked) {
              data.cart_ids.push(sku.cart_id)
            }
          })
        })
        if (data.cart_ids.length !== 0) {
          PutBatchDelCartItem(data).then(res => {
            const data = res.data
            if (data.status_code === 200) {
              this.$toast.success({
                duration: 1500,
                message: data.message
              })
              this.dataList = []
              this.searchData.p = 1
              this.getGoodsItemsList()
              this.$store.dispatch('setCartItemNumFn')
            } else {
              this.$toast.fail({
                duration: 1500,
                message: data.message
              })
            }
          })
        } else {
          this.$toast('请选择要删除的商品')
        }
      }
    },
    // 改变数量
    handleChangeSkuNum(sku) {
      if (sku.sku_num === 0 || !sku.sku_num) {
        sku.sku_num = 1
      }
      sku.sku_isChecked = true
      const data = {
        cart_id: sku.cart_id,
        num: sku.sku_num
      }
      setCartItemNum(data)
    },
    // 选中sku
    handleChangeSkuChecked(goodsItem, sku) {
      if (sku.sku_isChecked) {
        let num = 0
        goodsItem.sku_lists.forEach(sku => {
          if (sku.sku_isChecked) {
            num++
          }
        })
        if (num === goodsItem.sku_lists.length) {
          goodsItem.goods_isChecked = true
        }
      } else {
        goodsItem.goods_isChecked = false
      }
    },
    // 选中商品
    handleChangeGoodsChecked(goodsItem) {
      if (goodsItem.goods_isChecked) {
        goodsItem.sku_lists.forEach(sku => {
          sku.sku_isChecked = true
        })
        let num = 0
        this.dataList.forEach(item => {
          if (item.goods_isChecked) {
            num++
          }
        })
        if (num === this.dataList.length) {
          this.allChecked = true
        }
      } else {
        this.allChecked = false
        let num = 0
        goodsItem.sku_lists.forEach(sku => {
          if (sku.sku_isChecked) {
            num++
          }
        })
        if (num === goodsItem.sku_lists.length) {
          goodsItem.sku_lists.forEach(sku => {
            sku.sku_isChecked = false
          })
        }
      }
    },
    // 全选
    setAllChoose() {
      if (this.allChecked) {
        this.dataList.forEach(item => {
          item.goods_isChecked = true
          item.sku_lists.forEach(sku => {
            sku.sku_isChecked = true
          })
        })
      } else {
        let num = 0
        this.dataList.forEach(item => {
          if (item.goods_isChecked) {
            num++
          }
        })
        if (num === this.dataList.length) {
          this.dataList.forEach(item => {
            item.goods_isChecked = false
          })
        }
      }
    },
    // 获取选中商品的数量和价格
    getGoodsItemNumAndPrice(index) {
      let totalNum = 0
      let totalPrice = 0
      this.dataList[index].sku_lists.forEach(sku => {
        if (sku.sku_isChecked) {
          totalNum += sku.sku_num
          totalPrice += sku.sku_num * parseFloat(sku.price)
        }
      })
      return { totalNum, totalPrice }
    },
    // 获取选中商品的总数量和总价格
    getTotalNumAndPrice() {
      let totalNum = 0
      let totalPrice = 0
      let kindNum = 0
      this.dataList.forEach(item => {
        item.sku_lists.forEach(sku => {
          if (sku.sku_isChecked) {
            totalNum += sku.sku_num
            totalPrice += parseFloat(sku.price) * sku.sku_num
            kindNum++
          }
        })
      })
      return { totalNum, totalPrice, kindNum }
    },
    // 点击进入商品详情
    clickToGoodsDetail(id) {
      this.$router.push({ name: 'goods-detail', query: { goodsId: id }})
    },
    // 点击结算
    clickToOrder() {
      const obj = {
        item_ids: [],
        sku_ids: [],
        nums: [],
        is_cart: 1
      }
      this.dataList.forEach(item => {
        item.sku_lists.forEach(sku => {
          if (sku.sku_isChecked) {
            obj.item_ids.push(sku.item_id)
            if (sku.sku_id) {
              obj.sku_ids.push(sku.sku_id)
            } else {
              obj.sku_ids.push('')
            }
            obj.nums.push(sku.sku_num)
          }
        })
      })
      if (obj.item_ids.length !== 0) {
        this.$router.push({ name: 'shop-settlement', query: {
          itemData: JSON.stringify(obj)
        }})
      } else {
        this.$toast({
          duration: 1500,
          message: '请先选择商品'
        })
      }
    }
  }
}
</script>
<style lang="scss">
  @import "src/styles/mixin.scss";
  .van-cell{
    padding: pxCalc(15px) !important;
  }
  .van-collapse-item__content{
    padding: 0 pxCalc(15px)!important;
  }
  .van-icon.van-icon-arrow.van-cell__right-icon{
    position: absolute;
    bottom: pxCalc(10px);
    right: pxCalc(15px);
  }
  .van-checkbox{
    .van-checkbox__icon--checked .van-icon{
      color: #fff;
      border-color: #ff7340!important;
      background-color: #ff7340!important;
    }
  }
</style>
<style lang="scss" scoped>
  @import "src/styles/mixin.scss";

  .transform{
    transition: all 0.1s;
    transform: rotateZ(-90deg);
  }
  .icon{
    transition: all 0.1s;
    transform: rotateZ(90deg);
  }
  .mainContent{
    background-color: #fff;
    width: 100%;
    padding-bottom: pxCalc(110px);
    .header{
      width: 100%;
      padding: 0 pxCalc(20px);
      height: pxCalc(50px);
      position: fixed;
      z-index: 999;
      top: 0;
      background-color: #fff;
      border-bottom: 2px solid #eee;
      line-height: pxCalc(50px);
      display: flex;
      justify-content: space-between;
      .headerLeft{
        width: 50%;
        font-size: pxCalc(14px);
        font-weight: bold;
      }
      .headerRight{
        width: 50%;
        font-size: pxCalc(14px);
        color: #a1a1a1;
        span{
          float: right;
          padding-left: pxCalc(20px);
        }
      }
    }
    .contentList{
      width: 100%;
      padding-top: pxCalc(50px);
      .item{
        background-color: #fff;
        margin-bottom: pxCalc(10px);
        .title{
          width: 100%;
          display: flex;
          height: pxCalc(113px);
          padding:pxCalc(15px) pxCalc(20px);
          justify-content: space-between;
          flex-direction: row;
          position: relative;
          .titleLeft{
            width: pxCalc(30px);
            position: relative;
            line-height: pxCalc(80px);
          }
          .titleRight{
            width: 100%;
            position: relative;
            .leftImg{
              width: pxCalc(80px);
              height:pxCalc(80px);
              position: absolute;
            }
            .titleWord{
              height: 3em;
              padding-left:pxCalc(100px);
              display: inline-block;
              width: 100%;
              font-size: pxCalc(15px);
              overflow: hidden;
              text-overflow: ellipsis;
              word-break:break-all;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }
          }
          .iconBox{
            padding: pxCalc(5px);
            position: absolute;
            bottom: pxCalc(15px);
            right: pxCalc(20px);
          }
        }
        .item-content{
          max-height: pxCalc(260px);
          overflow-y: scroll;
          .content-list{
            width: 100%;
            padding: 0 pxCalc(20px);
            .list-item{
              width: 100%;
              height: pxCalc(55px);
              line-height: pxCalc(55px);
              margin-bottom: pxCalc(10px);
              display: flex;
              flex-direction: row;
              .titleLeft{
                width: pxCalc(30px);
              }
              .checkBox-content{
                display: flex;
                width: 100%;
                margin-right: pxCalc(-20px);
                padding-left: pxCalc(20px);
                padding-right: pxCalc(20px);
                flex-direction: row;
                justify-content: space-between;
                background-color: #fbfbfb;
                .left-item{
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  span{
                    display: inline;
                    line-height: 2em;
                  }
                }
                .right-item{
                  display: flex;
                  flex-direction: row;
                }
              }
            }
          }
        }
        .total-item{
          height: pxCalc(40px);
          padding-right: pxCalc(20px);
          margin-left: pxCalc(20px);
          border-top:  pxCalc(1px) solid #eee;
          line-height: pxCalc(40px);
          .total-itemNum{
            font-size: pxCalc(12px);
            color: #a1a1a1;
          }
          .total-itemPrice{
            font-size: pxCalc(16px);
            font-weight: bold;
            color: #ff0000;
            float: right;
          }
        }
      }
    }
    .footerBtn{
      position: fixed;
      bottom: pxCalc(55px);
      width: 100%;
      height: pxCalc(55px);
      background-color: #fff;
      border-bottom: 1px solid #eee;
      display: flex;
      .footerItem{
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: pxCalc(15px);
        display: inline;
      }
      .footerContent{
        height: 100%;
        font-size: pxCalc(14px);
        width: 100%;
        padding: 0 pxCalc(20px) 0 pxCalc(40px);
        display: flex;
        justify-content: space-between;
        .all{
          width: 3em;
          font-size: pxCalc(14px);
          line-height: pxCalc(55px);
        }
        .totalContent1{
          width: 100%;
          display: flex;
          padding: pxCalc(10px) 0;
          flex-direction: row;
          justify-content: flex-end;
          .content{
            line-height: 1.2em;
            text-align: right;
            min-width: 50%;
            .price{
              font-weight: bold;
              .int{
                font-size: pxCalc(20px);
              }
              .floor{
                font-size: pxCalc(14px);
              }
            }
            .tip{
              font-size: pxCalc(12px);
              padding-right: pxCalc(5px);
              color: #999999;
            }
          }
          .footerBtnItem{
            text-overflow: ellipsis;
            word-break: keep-all;
            font-size: pxCalc(12px);
            margin-left: pxCalc(10px);
            padding: pxCalc(7px) pxCalc(20px);
            color: #fff;
            position: relative;
            z-index: 999999;
            background: -webkit-linear-gradient(left,#ff4c38 0,#ff7f50 100%);
            border-radius: pxCalc(50px);
          }
        }
        .totalContent2{
          display: flex;
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          right: pxCalc(20px);
          justify-content: right;
          .btn{
            margin: 0 pxCalc(5px);
            /*border-radius: pxCalc(5px);*/
            &.btn-orange{
              background: #fff!important;
              border: pxCalc(1px) solid #ff7340;
              color: #ff7340;
            }
          }
        }
      }
    }
}
</style>
